package com.bw.lib_common.vm


import android.util.Log

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.bw.lib_common.entity.BaseEntity
import com.bw.lib_common.model.BaseRepository
import kotlinx.coroutines.*
import java.util.concurrent.Executors

/**
 * 基础的ViewModel
 */
abstract class BaseViewModel2<Repo: BaseRepository<*>>:ViewModel(){

    private val handler = CoroutineExceptionHandler { _, exception ->
        Log.e("Error", "Exception===>"+exception.message)
        mErrorLiveData.postValue("网络请求异常！")
    }

    //Dispatchers协程调度器，IO代表在子线程中开启协程，MAIN代表在主线程中开启协程，DEFAULT代表在业务调用的线程中开启协程，Unconfined代表没有特殊指定哪个线程中开启协程
    protected val mViewModelScope = CoroutineScope(Dispatchers.Main + SupervisorJob() + handler)

    //自定义协程线程池，并转换调度器
    protected val mDispatcher = Executors.newFixedThreadPool(16).asCoroutineDispatcher()
    //单线程的协程调度器
    protected val mSingleThreadDispatcher1 = newSingleThreadContext("singleThreadDispatcher")//方案二
    //国定大小的协程调度器
    protected val mFixThreadDispatcher2 = newFixedThreadPoolContext(16,"fixThreadDispatcher")//方案三




    //错误信息提示
    val mErrorLiveData  = MutableLiveData<String>()
    //数据获取成功
    val mSuccessLiveData  = MutableLiveData<BaseEntity>()

    protected val mRepository: Repo

    init {
        mRepository = createRepository()
    }

    //创建仓库
    protected abstract fun createRepository(): Repo

}